package dao

/*
厦门大学计算机专业 | 前华为工程师
专注《零基础学编程系列》  http://lblbc.cn/blog
包含：Java | 安卓 | 前端 | Flutter | iOS | 小程序 | 鸿蒙
公众号：蓝不蓝编程
*/
import (
	"gorm.io/gorm"
	"lblbc.cn/demo/entity"
)

type GoodsDao interface {
	QueryGoodsByCategory(categoryId string) []entity.Goods
	QueryGoods(goodsId string) entity.Goods
	SearchGoods(keyword string) []entity.Goods
}

type goodsDbConnection struct {
	connection *gorm.DB
}

func NewGoodsDao(connection *gorm.DB) GoodsDao {
	return &goodsDbConnection{connection: connection}
}

func (db *goodsDbConnection) QueryGoodsByCategory(categoryId string) []entity.Goods {
	var result []entity.Goods
	db.connection.Raw("SELECT g.id,g.name,g.price,g.square_pic squarePic,g.description FROM m_goods_category gc,m_goods g WHERE gc.goods_id=g.id AND gc.category_id=?", categoryId).Scan(&result)
	return result
}

func (db *goodsDbConnection) QueryGoods(goodsId string) entity.Goods {
	var result []entity.Goods
	db.connection.Raw("select g.id,g.name,g.price,g.square_pic squarePic,g.description from m_goods g where id=?", goodsId).Scan(&result)
	return result[0]
}

func (db *goodsDbConnection) SearchGoods(keyword string) []entity.Goods {
	var result []entity.Goods
	db.connection.Raw("select g.id,g.name,g.price,g.square_pic squarePic,g.description from m_goods g where name like ?", "%"+keyword+"%").Scan(&result)
	return result
}
